import { NodeSSH } from 'node-ssh';
import archiver from 'archiver';
import path from 'path';
import fs from 'fs';
import config from '../config.js';
import log from '../utils/log.js';
const projectDir = process.cwd();

const ssh = new NodeSSH();


// 开始打包
function startZip() {
    let { distPath, host } = config;
    distPath = path.resolve(projectDir, distPath);
    console.log('(2) 打包成zip...');
    const archive = archiver('zip', {
        zlib: { level: 9 },
    }).on('error', err => {
        throw err;
    });
    const output = fs.createWriteStream(`${projectDir}/dist.zip`).on('close', err => {
        if (err) {
            log.error('  关闭archiver异常:', err);
            return;
        }
        log.success('  zip打包成功');
        console.log(`(3) 连接 ${log.underline(host)}`);
        uploadFile();
    });
    archive.pipe(output);
    archive.directory(distPath, '/');
    archive.finalize();
}

// 上传文件
function uploadFile() {
    const { host, port, username, password, privateKey, passphrase } = config;
    const sshConfig = {
      host,
      port,
      username,
      password,
      privateKey,
      passphrase
    };
    ssh.connect(sshConfig)
        .then(() => {
            log.success(`  SSH连接成功`);
            console.log(`（4）上传zip至目录  ${log.underline(config.webDir)}`);
            console.log(projectDir)
            
            ssh.putFile(`${projectDir}/dist.zip`, `${config.webDir}/dist.zip`)
            .then(() => {
                log.success(`  zip包上传成功`);
                console.log('（5）解压zip包');
                statrRemoteShell(config);
            })
            .catch(err => {
                log.error('  文件传输异常', err);
                process.exit(0);
            });
        })
        .catch(err => {
            log.error('  连接失败', err);
            process.exit(0);
        });
}

// 执行Linux命令
function runCommand(command, webDir) {
    return new Promise((resolve, reject) => {
      ssh.execCommand(command, { cwd: webDir })
        .then(result => {
            resolve();
            // if (result.stdout) {
            //   log.success(result.stdout);
            // }
            if (result.stderr) {
                log.error(result.stderr);
                process.exit(1);
            }
        })
        .catch(err => {
          reject(err);
        });
    });
}

// 开始执行远程命令
function statrRemoteShell(config) {
    const { webDir } = config;
    const commands = [`cd ${webDir}`, 'pwd', 'unzip -o dist.zip && rm -f dist.zip'];
    const promises = [];
    for (let i = 0; i < commands.length; i += 1) {
      promises.push(runCommand(commands[i], webDir));
    }
    Promise.all(promises)
        .then(() => {
            log.success('  解压成功');
            console.log('（6）开始删除本地dist.zip');
            deleteLocalZip(config);
        })
        .catch(err => {
            log.error('  文件解压失败', err);
            process.exit(0);
        });
  }
  
  // 删除本地dist.zip包
function deleteLocalZip(config) {
    const { projectName, name } = config;
    fs.unlink(`${projectDir}/dist.zip`, err => {
        if (err) {
            log.error('  本地dist.zip删除失败', err);
        }
        log.success('  本地dist.zip删除成功\n');
        log.success(`\n 恭喜您，${log.underline(projectName)}项目${log.underline(name)}部署成功了^_^\n`);
        process.exit(0);
    });
}
  


startZip()